package kr.co.cooknote.dashboard.controller;

import java.util.List;
import java.util.Map;

import javax.validation.Valid;

import kr.co.cooknote.dashboard.domain.User;
import kr.co.cooknote.dashboard.domain.UserList;
import kr.co.cooknote.dashboard.mapper.UserMapper;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.support.SessionStatus;

@Controller
//@RequestMapping("/v1")
public class UserController  {

	@Autowired
	private Environment environment;

	@Autowired
	UserMapper userMapper;



	private static final Logger logger = LoggerFactory.getLogger(UserController.class);


/////////////////////////////////////기본 crud 시작  ////////////////////////////////////////////

    @RequestMapping(value = "/user_list_form", method = RequestMethod.GET)
    public String userListForm(@Valid User user, Map<String, Object> model) {
    	User u = new User();
    	u.setNick_name("강진규");
    	u.setUser_id("captinkd");
        model.put("userm", u);
        return "dashboard/userList";
    }

	// this method responses to GET request http://localhost:8080/api/vi/faq
	// return Faq object as json
	@RequestMapping(value = "/user_list", method = RequestMethod.POST)
	@ResponseBody
	public List<User> getUser(@Valid User user, BindingResult bindingResult, SessionStatus status, Model model) {
	//public List<User> getUser(@Valid User user, BindingResult bindingResult, SessionStatus status) {
//	public String signup(@Valid SignupForm form, BindingResult formBinding, final WebRequest request) {
//	public String sendInvites(@Valid MailInviteForm form, BindingResult result, Account account, RedirectAttributes redirectAttrs) {
//	public String update(@PathVariable String slug, @Valid AppForm form, BindingResult bindingResult, Account account, Model model) {
//	public List<User> getUser(@Valid User user, BindingResult bindingResult, Account account) {
	//public List<User> getFaqs(@RequestParam(value="name", required=false, defaultValue="World") String name, Model model) {

//        if (bindingResult.hasErrors()) {
//            return "owners/createOrUpdateOwnerForm";
//        } else {
//            this.clinicService.saveOwner(owner);
//            status.setComplete();
//            return "redirect:/owners/" + owner.getId();

		model.addAttribute("users", userMapper.getUsers());

		return userMapper.getUsers();
//		return "dashboard/userList";

	}


    @RequestMapping(value = "/user_create_form", method = RequestMethod.GET)
    public String initFindForm(@Valid User user, Map<String, Object> model) {
    	User u = new User();
    	u.setNick_name("강진규");
    	u.setUser_id("captinkd");
        return "dashboard/userCreate";
    }

	// this method response to POST request http://localhost:8080/api/v1/user
	// receives json data sent by client --> map it to User object
	// return User object as json
	@RequestMapping(value = "/user_create", method = RequestMethod.POST)
	@ResponseBody
	public User saveUser(@Valid User user, Model model) {
		logger.info("Save call: "+ user.getUser_id() + ", " + user.getNick_name());

		System.out.println("insertCount==="+environment.getProperty("insertCount"));
		System.out.println("selectError==="+environment.getProperty("selectError"));
		System.out.println("selectWarn==="+environment.getProperty("selectWarn"));

		userMapper.saveUser(user);
		return user;
	}



    @RequestMapping(value = "/user_detail_form", method = RequestMethod.GET)
    public String userDetailForm(@Valid User user, Map<String, Object> model) {
    	User u = new User();
    	u.setNick_name("강진규");
    	u.setUser_id("captinkd");
        model.put("userm", u);
        model.put("userDetail", userMapper.getUser(user));
        return "dashboard/userDetail";
    }

	// this method response to POST request http://localhost:8080/api/v1/user
	// receives json data sent by client --> map it to User object
	// return User object as json
	@RequestMapping(value = "/user_detail", method = RequestMethod.POST)
	@ResponseBody
	public User getUser(@Valid User user, Model model) {
		logger.info("detail call: "+ user.getUser_id() + ", " + user.getNick_name());

		System.out.println("insertCount==="+environment.getProperty("insertCount"));
		System.out.println("selectError==="+environment.getProperty("selectError"));
		System.out.println("selectWarn==="+environment.getProperty("selectWarn"));

		return userMapper.getUser(user);
	}



    @RequestMapping(value = "/user_update_form", method = RequestMethod.GET)
    public String userUpdateForm(@Valid User user, Map<String, Object> model) {
    	User u = new User();
    	u.setNick_name("강진규");
    	u.setUser_id("captinkd");
        model.put("userm", u);
        return "dashboard/userUpdate";
    }


	@RequestMapping(value = "/user_update", method = RequestMethod.POST)
	@ResponseBody
	public User updateUser(@Valid  User user) {
		logger.info("Update call: "+ user.getUser_id() + ", " + user.getNick_name());
		userMapper.updateUser(user);
		return user;
	}



	@RequestMapping(value = "/user_delete", method = RequestMethod.POST)
	@ResponseBody
	public User deleteUser(@Valid User user, Model model) {
		logger.info("Delete call: "+ user.getUser_id() + ", " + user.getNick_name());

		System.out.println("insertCount==="+environment.getProperty("insertCount"));
		System.out.println("selectError==="+environment.getProperty("selectError"));
		System.out.println("selectWarn==="+environment.getProperty("selectWarn"));

		userMapper.deleteUser(user);
		return user;
	}











///////////////////////////////////////기본 crud 끝 ////////////////////////////////////////////



	@Value("${insertCount}")
	private String insertCount;
	@Value("${selectError}")
	private String selectError;
	@Value("${selectWarn}")
	private String selectWarn;

	@RequestMapping(
			value = "/users"
			, method = RequestMethod.GET
			, produces={"application/xml", "application/json"}
//			, headers="Accept=*/*"
			, headers="Accept=application/xml, application/json"
	)
	@ResponseStatus(HttpStatus.OK)
	@ResponseBody
	public  UserList users(Model model ) {
		logger.info("#### Select XML call: "+ 4);

		System.out.println("insertCount==="+insertCount);
		System.out.println("selectError==="+selectError);
		System.out.println("selectWarn==="+selectWarn);
		System.out.println("insertCount==="+environment.getProperty("insertCount"));
		System.out.println("selectError==="+environment.getProperty("selectError"));
		System.out.println("selectWarn==="+environment.getProperty("selectWarn"));


		return new UserList(userMapper.getUsers());
	}
	@RequestMapping(
			value = "/user"
			, method = RequestMethod.GET
			, produces={"application/xml", "application/json"}
//			, headers="Accept=*/*"
			, headers="Accept=application/xml, application/json"
	)
	@ResponseStatus(HttpStatus.OK)
	@ResponseBody
	public  User user(@Valid User user, Model model) {
		logger.info("#### Select XML call: "+ 4);

		System.out.println("insertCount==="+insertCount);
		System.out.println("selectError==="+selectError);
		System.out.println("selectWarn==="+selectWarn);
		System.out.println("insertCount==="+environment.getProperty("insertCount"));
		System.out.println("selectError==="+environment.getProperty("selectError"));
		System.out.println("selectWarn==="+environment.getProperty("selectWarn"));


//		return userMapper.getUser("s11");
		return userMapper.getUser(user);
	}







	@RequestMapping(value = "/user", method = RequestMethod.GET)
//	@ResponseBody
	public void getUsers(Model model ) {
		logger.info("Select all call: "+ 3);
		logger.info("Select all call: "+ 3);

//		insertCount
		model.addAttribute("users", userMapper.getUsers());

	}




//  @RequestMapping("/hello")
//  public void hello(@RequestParam(value="name", required=false, defaultValue="World") String name, Model model) {
//
//      model.addAttribute("name", name);
//      System.out.println("### name="+name);
//
//
//  }



//	  @RequestMapping("/test/mybatis/{userId}")
//	  @ResponseBody
//	  public String testMybatis(@PathVariable("userId") String userId)
//	  {
//	    ExampleDao exampleDao = sqlSession.getMapper(ExampleDao.class);
//	    return exampleDao.getUserName(userId);
//	  }



//	// this method responses to GET request http://localhost:8080/api/vi/user/{id}
//	// return User object as json
//	@RequestMapping(value = "/user/{id}", method = RequestMethod.GET)
//	@ResponseBody
//	public User getById(@PathVariable Integer id) {
//		User user = this.userService.getById(id);
//		logger.info("Select one call: "+ user.getId() + ", " + user.getName());
//		return user;
//	}



//	@RequestMapping(value = "/user/{id}", method = RequestMethod.DELETE)
//	@ResponseBody
//	public void deleteUser(@PathVariable Integer id) {
//		logger.info("Delete call: "+ id);
//		this.userService.delete(id);
//	}




}